from django.shortcuts import render
import datetime, requests
# Create your views here.
from django.db import transaction
from django.utils import timezone
from django.contrib.auth import get_user_model

from rest_framework import viewsets
from rest_framework.views import APIView
from rest_framework import generics
from rest_framework.serializers import ValidationError
from utils import response_error, response_ok
from utils.permission import IsMemberUser
from utils.exception import CustomError

from .serializers import (MemberMobileSignSerializer, MemberLoginByPwdSerializer, MemberObtainSerializer,
                          MemberSerializer)
from apps.system.models import VCode, Log
from .models import Member, MemberNameLog

User = get_user_model()


class MemberTestLoginView(APIView):

    def post(self, request):
        print(request.data['code'])
        APPID = 'wx1485290d97a26159'
        SECRET = '1b50ad60fcbfa7dc80db56365eef85ae'
        #
        url = 'https://api.weixin.qq.com/sns/jscode2session?appid={APPID}&secret={SECRET}&js_code={JSCODE}&grant_type=authorization_code'.format(
            APPID=APPID, SECRET=SECRET, JSCODE=request.data['code'])
        res = requests.get(url)
        print('-------------------')
        print(res.json())
        return response_ok()


class MemberLoginView(APIView):
    serializer_class = MemberMobileSignSerializer

    def post(self, request, *args, **kwargs):
        """验证码注册登录"""
        ser = self.serializer_class(data=request.data)
        if ser.is_valid():
            return response_ok(ser.validated_data)
        return response_error('手机号或者验证码错误！')


class MemberLoginByPwdView(APIView):
    serializer_class = MemberLoginByPwdSerializer

    def post(self, request):
        try:
            ser = self.serializer_class(data=request.data)
            if ser.is_valid(raise_exception=True):
                return response_ok(ser.validated_data)
        except ValidationError as e:
            return response_error(e.detail)


class MemberResetPasswordView(APIView):
    permission_classes = [IsMemberUser]

    def post(self, request):
        data = request.data
        user = request.user
        if not data['vcode']:
            raise CustomError('请输入验证码！')
        if not data['password']:
            raise CustomError('请输入密码！')
        # 验证验证码
        VCode.verify(user.username, data['vcode'], VCode.FORGET_PASSWORD)
        with transaction.atomic():
            user.set_password(data['password'])
            user.save()
            Log.objects.addLog(user, Log.UPDATE, '会员[%s]修改密码,id=%d' % (user.username, user.id))
        return response_ok()


class MemberObtainView(generics.RetrieveAPIView):
    """检索成员信息"""
    permission_classes = (IsMemberUser,)
    queryset = Member.objects.filter()
    serializer_class = MemberObtainSerializer

    def get_object(self):
        queryset = self.filter_queryset(self.get_queryset())
        print(self.get_queryset())
        obj = queryset.filter(user=self.request.user).first()
        return obj

    def retrieve(self, request, *args, **kwargs):
        isinstance = self.get_object()
        serializer = self.get_serializer(isinstance)
        return response_ok(serializer.data)


class MemberEditInfoView(APIView):
    permission_classes = (IsMemberUser,)

    def post(self, request):
        data = request.data
        member = request.user.member

        name = data['name']
        # 检查是否允许修改昵称
        if name and name != request.user.name:
            if member.level == Member.COMMON:
                return response_error('你不是会员不可更新昵称！')

            start_time = timezone.now() + datetime.timedelta(days=-30)
            print(start_time)
            count = MemberNameLog.objects.filter(create_time__gt=start_time, member=request.user).count()
            if count:
                raise CustomError('VIP会员30天内只能修改一次昵称')

            # 检查昵称的合法性
            result = Member.check_name_legal(name)
            if result:
                raise CustomError('昵称中包含敏感词[%s],不能进行修改！' % result)

            count = User.objects.filter(name=name).count()
            if count:
                raise CustomError('该昵称已被占用')

        try:
            with transaction.atomic():
                # 昵称日志
                MemberNameLog.objects.create(member=request.user, old_name=member.user.name, new_name=name)
                request.user.name = name

                # 更新user上的字段
                if data['gender']:
                    request.user.gender = data['gender']
                request.user.save()

                # 更新member上的字段
                fields = {}
                if data['headImage']:
                    fields['headImage'] = data['headImage']

                Member.objects.filter(id=member.id).update(**fields)
                Log.objects.addLog(self.request.user, Log.UPDATE, '会员[%s]修改信息，id=%id' % (member.user.name, member.id))
        except Exception as e:
            # import traceback
            # traceback.print_exc()
            return response_error(str(e))

        return response_ok()


class GroupViewSet(viewsets.ModelViewSet):
    queryset = Member.objects.all()
    serializer_class = MemberSerializer
